<template>
    <a-select v-model="selected" :defaultValue="selected" :disabled="disabled" :placeholder="placeholder">
      <a-select-option  :value="emptyKey" v-if="showEmpty">{{emptyLabel}}</a-select-option>
      <a-select-option :value="key" :key="key" v-for="(value, key) in data">{{value}}</a-select-option>
    </a-select>
</template>

<script>
  import {prefix} from '../config';
  import {constantNameMap} from '../../../constants';
  export default {
    name: prefix + 'ConstantSelect',
    props: {
      value: {
        default: ''
      },
      allowClear: {
        type: Boolean,
        required: false,
        default: false
      },
      type: {
        type: String,
        required: true,
        default: ''
      },
      emptyLabel: {
        type: String,
        default: '全部'
      },
      emptyKey: {
        type: String,
        default: ''
      },
      showEmpty: {
        type: Boolean,
        default: true
      },
      invalidKeys: {
        type: String,
        default: ''
      },
      customOption: {
        type: Object
      },
      disabled: {
        type: Boolean,
        default: false
      },
      placeholder: {
        type: String,
        default: '请选择'
      }
    },
    data () {
      return {
        selected: this.value
      };
    },
    computed: {
      data () {
        let constant = constantNameMap[this.type];
        let retObj = {};
        if (constant) {
          let invalidKeys = ',' + this.invalidKeys + ',';
          for (let key in constant) {
            if (invalidKeys.indexOf(',' + key + ',') !== -1) {
              continue;
            }
            retObj[key] = constant[key];
          }
        }
        if (this.customOption) {
          retObj = {...retObj, ...this.customOption};
        }
        return retObj;
      }
    },
    watch: {
      value (val) {
        if (this.selected === val) {
          return;
        }
        this.selected = val;
      },
      selected (val, oldVal) {
        this.$emit('input', val);
        this.$emit('change', val, oldVal);
      }
    }
  };
</script>

<style>

</style>
